//
// Unihan Input Method
//
// Copyright © 2002-2007 Sun Wah Linux Ltd.
//
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 2.1 of the
// License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
// USA
//
// $Id: tc_sc.c 800 2007-07-25 02:52:29Z roger $
//

/*
** $Id: tc_sc.c 800 2007-07-25 02:52:29Z roger $
*/

#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif

#include "tc_sc.h"

#include <stdlib.h>

/**
 * @defgroup TCSC Traditonal/Simplified Chinese conversion
 * @{
 */

typedef struct {
	UTF32CHAR orig;
	UTF32CHAR needed;
} MappingTable;
#include "tc2sc.tab"
#include "sc2tc.tab"

typedef struct {
	MappingTable *table;
	size_t tab_size;
} Mapping;

static Mapping tc2sc_map = { tc2sc, TC2SC_SIZE };
static Mapping sc2tc_map = { sc2tc, SC2TC_SIZE };

static void real_convert(UTF32CHAR *, Mapping *);
static int compare_char(const void *, const void *);

static int
compare_char(const void *key, const void *memb)
{
	MappingTable *mapping = (MappingTable *)memb;
	UTF32CHAR *orig = (UTF32CHAR *)key;

	return (*orig - mapping->orig);
}

static void
real_convert(UTF32CHAR *str, Mapping *map)
{
	if (!str)
		return;

	while (*str) {
		MappingTable *found = NULL;
		found = (MappingTable *)bsearch(str, map->table, map->tab_size, 
						sizeof(MappingTable), 
						compare_char);
		if (found != NULL) {
			*str = found->needed;
		}

		++str;
	}
}

/**
 * @brief Converts \a str from Traditional Chinese to Simplified Chinese in place.
 *
 * @param str   a UTF-32 string
 */
void
convert_tc_to_sc(UTF32CHAR *str)
{
	real_convert(str, &tc2sc_map);
}

/**
 * @brief Converts \a str from Simplified Chinese to Traditional Chinese in place.
 *
 * @param str   a UTF-32 string
 */
void
convert_sc_to_tc(UTF32CHAR *str)
{
	real_convert(str, &sc2tc_map);
}

/** @} */
// vi:ts=4:sw=4:nowrap:cin:expandtab
